<template>
  <div class="light">
    <div class="light-top">
      <div v-for="item in lights" :key="item.color"></div>
    </div>
    <div class="pole"></div>
    <div class="stone"></div>
  </div>
</template>

<script>
export default {
  name: "RedStreetLight",
  data() {
    return {
      flash: false,
      lights: [
        { color: "red", duration: 5000, twinkleDuration: 2000 },
        { color: "green", duration: 6000, twinkleDuration: 2000 },
        { color: "yellow", duration: 10000, twinkleDuration: 5000 },
        { color: "blue", duration: 1000, twinkleDuration: 0 },
      ],
    };
  },
  mounted() {
    this.blink();
  },
  methods: {
    changeColor(color, num) {
      let lightItem = document.querySelectorAll(".light-top>div");

      // 将上一轮加的颜色调回来
      for (let i = 0; i < lightItem.length; i++) {
        lightItem[i].style.backgroundColor = "black";
        lightItem[i].className = ""; // 停止闪烁
      }
      // 给传入的灯设置颜色
      lightItem[num].style.backgroundColor = color;
    },
    changeT(num) {
      let lightItem = document.querySelectorAll(".light-top>div");
      for (let i = 0; i < lightItem.length; i++) {
        lightItem[i].className = "";
      }
      lightItem[num].className = "flash";
    },

    light(currentLight, num) {
      const currentColor = currentLight.color;
      const interval = currentLight.duration;
      const flashTime = interval - currentLight.twinkleDuration;
      return new Promise((resolve) => {
        this.changeColor(currentColor, num);

        // 20-5       15秒后开始闪烁
        if (flashTime > 0) {
          setTimeout(() => {
            this.changeT(num); // 开始闪缩
          }, flashTime);
        }
        setTimeout(resolve, interval);
      });
    },

    async blink() {
      for (const [key, item] of this.lights.entries()) {
        await this.light(item, key);
      }
      await this.blink();
    },
  },
};
</script>

<style scoped>
@keyframes myAnimation {
  0% {
    opacity: 0;
    filter: alpha(opacity=0);
  }
  100% {
    opacity: 1;
    filter: alpha(opacity=100);
  }
}
.flash {
  -webkit-animation: myAnimation 0.6s infinite;
  animation: myAnimation 0.6s infinite;
}
.light-top {
  /* height: 30em; */
  width: 10em;
  padding: 1em 2em;
  border-radius: 5em;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  background-color: #383838;
}

.light-top > div {
  width: 8em;
  height: 8em;
  border-radius: 50%;
  background-color: #000000;
  opacity: 0.8;
  transition: all 0.3s ease-in;
}

.light {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.pole {
  width: 4em;
  height: 8em;
  background-color: #383838;
}

.stone {
  width: 14em;
  height: 2.5em;
  background-color: #383838;
  border-radius: 1em;
}
</style>
